//
//  GHRefresh.swift
//  下拉刷新
//
//  Created by  郭航 on 16/7/1.
//  Copyright © 2016年 郭航. All rights reserved.
//

import UIKit

//private let SCREENW: CGFloat = UIScreen.mainScreen().bounds.size.width

private let refreshH: CGFloat = 50

private let viewKeyPath = "contentOffset"

enum GHRefreshType: String {
    /// 下拉刷新
    case Normal = "下拉刷新"
    /// 松开刷新
    case Pulling = "松手刷新"
    /// 正在刷新
    case Refresh = "正在刷新"
}

class GHRefresh: UIControl {
    
    private var superView: UIScrollView?
    
    private var refreshType: GHRefreshType = .Normal {
        didSet {
            textLabel.text = refreshType.rawValue
            
            if refreshType == .Normal {
                if oldValue == .Refresh {
                    UIView.animateWithDuration(0.25, animations: { 
                        self.superView?.contentInset.top -= refreshH
                    })
                }
            } else if refreshType == .Refresh {
                UIView.animateWithDuration(0.25, animations: {
                        self.superView?.contentInset.top += refreshH
                    }, completion: { (_) in
                        self.sendActionsForControlEvents(.AllEvents)
                })
            }
        }
    }
    
    private lazy var textLabel: UILabel = {
        let label = UILabel()
        
        label.text = self.refreshType.rawValue
        
        //MARK: - 调整字体颜色
        label.textColor = UIColor.orangeColor()
        label.textAlignment = .Center
        label.font = UIFont.systemFontOfSize(20)

        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -refreshH, width: SCREENW, height: refreshH))
        
        //MARK: - 调整背景颜色
        backgroundColor = UIColor.whiteColor()
        
        addSubview(textLabel)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        textLabel.frame = CGRect(x: 0, y: 0, width: SCREENW, height: refreshH)
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let superView = newSuperview as? UIScrollView else {
            return
        }
        
        self.superView = superView
        
        superView.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        guard let obj = object as? UIScrollView where obj == superView && keyPath! == viewKeyPath else {
            return
        }
        
        let contentOffSetY = superView!.contentOffset.y
        
        let contentInSetTop = superView!.contentInset.top
        
        if superView!.dragging {
            if contentOffSetY <= -(contentInSetTop + refreshH) && refreshType == .Normal {
                refreshType = .Pulling
            } else if contentOffSetY > -(contentInSetTop + refreshH) && refreshType == .Pulling {
                refreshType = .Normal
            }
        } else {
            if refreshType == .Pulling {
                refreshType = .Refresh
            }
        }
    }
    
    func endRefreshing() -> Void {
        refreshType = .Normal
    }
    
    deinit {
        self.superView?.removeObserver(self, forKeyPath: viewKeyPath)
    }
    
}
